<?php

namespace app\admin\controller\member;

use app\common\controller\Backend;
use app\common\controller\Checking;
use think\console\output\question\Choice;
use think\Db;
use think\Exception;
/**
 * 用户管理
 *
 * @icon fa fa-users
 */
class Users extends Backend
{
    
    /**
     * Users模型对象
     * @var \app\admin\model\member\Users
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\member\Users;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("levelList", $this->model->getLevelList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with('getusers')
                ->where($where)
                ->order('users.id', $order)
                ->count();
            $list = $this->model
                ->with('getusers')
                ->where($where)
                ->order('users.id', $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $insert=[];
                    $phone=Db::name('users')->where(['mobile'=>$params['mobile']])->find();
                    if (!empty($phone)){
                        $this->error('该手机号已注册');
                    }
                    if ($params['pid']==''){
                        $this->error('推荐人有误');
                    }
                    $pid = 0;
                    if ( $params['pid'] ) {
                        $father = Db::name( 'users' )->where('mobile',$params['pid'])->field( 'id' )->find();
                        if ( !$father ) {
                            $this->error('推荐人有误');
                        }
                        $pid = $father['id'];
                    }
                    $chars ='0123456789';
                    do {
                        $codes = "";
                        for ( $i = 0; $i < 6; $i++ ) {
                            $codes .= substr( $chars, mt_rand( 0, strlen( $chars ) - 1 ), 1 );
                        }
                    } while (Db::name('users')->where('uuid',$codes)->count());
                    $insert['pid']=$pid;
                    $insert['mobile']=$params['mobile'];
                    $insert['password']=password_hash( $params['password'], PASSWORD_DEFAULT );
                    $insert['uuid']=$codes;
                    $insert['level']=4;
                    $insert['nickname']= $params['nickname'];
                    $insert['truename']= $params['truename'];
                    $insert['createtime']= date( 'YmdHis' );
                    $send_vip=Db::name('config')->where('name','send_vip')->field('value')->find();
                    $vip_time=time()+86400*$send_vip['value'];
                    $insert['vip_expire_time']=date('Y-m-d H:i:s',$vip_time);
                    $newId=Db::name('users')->insertGetId($insert);
                    if ($newId != null) {
                        if ( $newId && $pid > 0 ) {
                            $position = Db::name('users_position')
                                ->where( 'user_id', $pid )
                                ->select();
                            $action = [];
                            if ( $position ) {
                                $action[0]['user_id'] = $newId;
                                $action[0]['pid'] = $pid;
                                $action[0]['lay'] = 1;
                                $action[0]['create_time'] = $insert['createtime'];
                                foreach ( $position as $k => $v ) {
                                    $action[ $k + 1 ]['user_id'] = $newId;
                                    $action[ $k + 1 ]['pid'] = $v['pid'];
                                    $action[ $k + 1 ]['lay'] = $v['lay'] + 1;
                                    $action[ $k + 1 ]['create_time'] = $insert['createtime'];
                                }
                                Db::name('users_position')->insertAll($action );
                            } else {
                                $action['user_id'] = $newId;
                                $action['pid'] = $pid;
                                $action['lay'] = 1;
                                $action['create_time'] = $insert['createtime'];
                                Db::name('users_position')->insert($action);
                            }
                        }
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 充值
     * @param null $ids
     */
    public function recharge($ids = null){

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            try {
                if($params['balance']>0){
                    db('users_account_log')->insert([
                        'user_id'=>$ids,
                        'coin_type'=>'study',
                        'type'=>9,
                        'class'=>1,
                        'money'=>$params['balance'],
                        'remark'=>'后台充值',
                        'createtime'=>date('YmdHis'),
                        'before_money'=>$params['money']
                    ]);
                    $result=db('users')->where('id',$ids)->setInc('balance',$params['balance']);
                }
                if($params['lover']>0){
                    db('users_account_log')->insert([
                        'user_id'=>$ids,
                        'coin_type'=>'love',
                        'type'=>9,
                        'class'=>1,
                        'money'=>$params['lover'],
                        'remark'=>'后台充值',
                        'createtime'=>date('YmdHis'),
                        'before_money'=>$params['loves']
                    ]);
                    $result=db('users')->where('id',$ids)->setInc('lover',$params['lover']);
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error($row->getError());
                }
            } catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
            } catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
        }
        $userinfo=db('users')->where('id',$ids)->field('balance,lover')->find();
        $this->view->assign("userinfo", $userinfo);
        return $this->view->fetch();
    }

    /**
     * 设置为超级会员
     */
    function super_vip($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        $user_info=db('users')->where('id',$ids)->find();
        $pid=$user_info['pid'];

            $puser_info=db('users')->where('id',$pid)->find();//上级个人信息
            $phas=db('users_account_log')->where('user_id',$pid)->where('source_id',$ids)->where('type',3)->find();
            if($pid!=0&&!$phas){
                $agent_translate=db('config')->where('name','agent_translate')->value('value');
                $agent_translate_value=db('config')->where('name','agent_translate_value')->value('value');
                $agent_translate_money=$agent_translate/100*$agent_translate_value;
                db('users')->where('id',$pid)->setInc('balance',$agent_translate_money);
                db('users_account_log')->insert([
                    'user_id'=>$pid,
                    'source_id'=>$ids,
                    'coin_type'=>'study',
                    'type'=>3,
                    'class'=>1,
                    'money'=>$agent_translate_money,
                    'remark'=>'奖金比例:'.$agent_translate/100,
                    'createtime'=>date('YmdHis'),
                    'before_money'=>$puser_info['balance']
                ]);
            }
            $update=db('users')->where('id',$ids)->update(['level'=>3,'super_vip'=>date('YmdHis')]);
            if($update){
                $this->success();
            }else{
                $this->error('设置失败');
            }
    }



}
